1 package ch.odi.justblog.discovery; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.net.MalformedURLException; 6 import java.net.URL; 7 import java.util.ArrayList; 8 9 import javax.xml.parsers.DocumentBuilder; 10 import javax.xml.parsers.DocumentBuilderFactory; 11 import javax.xml.parsers.ParserConfigurationException; 12 13 import org.w3c.dom.Document; 14 import org.w3c.dom.NamedNodeMap; 15 import org.w3c.dom.Node; 16 import org.w3c.dom.NodeList; 17 import org.xml.sax.SAXException; 18 19 import ch.odi.util.xml.NodeEnumeration; 20 21 /*** 22 * RSD is Really Simple Discoverability 1.0 as defined by 23 * http://archipelago.phrasewise.com/rsd. This class is responsible for reading a RSD file 24 * and providing it's information to the application. 25 * 26 * @author oglueck 27 */ 28 public class Rsd { 29 private static final String version="1.0"; 30 private ArrayList apiList; 31 32 /*** 33 * Reads and parses an RSD file. 34 * 35 * @param xml the RSD data 36 * @param context the context URL used to resolve relative URLs. This should be the URL of 37 * the RSD file usually. 38 * @throws InvalidDocumentException 39 */ 40 public Rsd(InputStream xml, URL context) throws InvalidDocumentException { 41 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 42 DocumentBuilder builder; 43 try { 44 builder = factory.newDocumentBuilder(); 45 Document doc = builder.parse(xml); 46 NodeList apis = doc.getElementsByTagName("api"); 47 apiList = new ArrayList(apis.getLength()); 48 NodeEnumeration i = new NodeEnumeration(apis); 49 while (i.hasMoreElements()) { 50 Node api = (Node) i.nextElement(); 51 NamedNodeMap atts = api.getAttributes(); 52 try { 53 String name = atts.getNamedItem("name").getNodeValue(); 54 boolean preferred = "true".equalsIgnoreCase(atts.getNamedItem("preferred").getNodeValue()); 55 URL apiUrl = new URL(context, atts.getNamedItem("apiLink").getNodeValue()); 56 String blogId = atts.getNamedItem("blogID").getNodeValue(); 57 apiList.add(new RsdApi(name, preferred, apiUrl, blogId)); 58 } catch(NullPointerException e) { 59 continue; 60 } catch(MalformedURLException e) { 61 continue; 62 } 63 } 64 } catch (ParserConfigurationException e) { 65 throw new InvalidDocumentException(e); 66 } catch (SAXException e) { 67 throw new InvalidDocumentException(e); 68 } catch (IOException e) { 69 throw new InvalidDocumentException(e); 70 } 71 } 72 73 /*** 74 * Returns the supported version of the RSD specs. 75 * 76 * @return version string 77 */ 78 public static String getVersion() { 79 return version; 80 } 81 82 public RsdApi[] getApis() { 83 return (RsdApi[]) apiList.toArray(new RsdApi[apiList.size()]); 84 } 85 86 }